package com.lagou.controller;


import com.lagou.dao.ResumeDao;
import com.lagou.pojo.Result;
import com.lagou.pojo.Resume;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Optional;

/**
 * @author : zhengyao3@郑瑶
 * @date : 2020/5/20 16:51
 * @Description: resume控制类
 */
@RequestMapping("/resume")
@Controller
public class ResumeController {
    
    @Autowired
    private ResumeDao resumeDao;
    
    
    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(ArithmeticException exception, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg",exception.getMessage());
        modelAndView.setViewName("error");
        return modelAndView;
    }
    
    @PostMapping("/delete")
    @ResponseBody
    public Result delete(Long id){
        System.out.println("delete id = " +id);
        resumeDao.deleteById(id);
        Result result = new Result();
        result.setCode("success");
        result.setMsg("删除id:" + id + "成功");
        return result;
    }
    
    @GetMapping("/list")
    public ModelAndView list(){
        ModelAndView modelAndView = new ModelAndView();
        List<Resume> resumeList = resumeDao.findAll();
        modelAndView.addObject("list", resumeList);
        modelAndView.setViewName("list");
        return modelAndView;
    }

    @PostMapping("/save")
    public String save(Resume resume){
        resumeDao.save(resume);
        Result result = new Result();
        result.setCode("success");
        result.setMsg("保存成功");

        return "redirect:list";
    }

    @PostMapping("/update")
    public String update(Resume resume){
        resumeDao.save(resume);
        Result result = new Result();
        result.setCode("success");
        result.setMsg("修改成功");

        return "redirect:list";
    }
    
    @GetMapping("/edit")
    public ModelAndView toFormPage(@RequestParam(value = "id" ,required = false) Long id){
        ModelAndView modelAndView = new ModelAndView();
        if (id != null) {
            Optional<Resume> byId = resumeDao.findById(id);
            Resume resume = byId.get();
            modelAndView.addObject("id", resume.getId());
            modelAndView.addObject("address",resume.getAddress());
            modelAndView.addObject("name", resume.getName());
            modelAndView.addObject("phone", resume.getPhone());
        }
        modelAndView.setViewName("resumeForm");
        return modelAndView;
    }
    
}
